package com.jiuzhe.commercial.ui.house;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.example.zhouwei.library.CustomPopWindow;
import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.base.BaseActivity;
import com.jiuzhe.commercial.bean.HouseInfoBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;
import com.jiuzhe.commercial.view.CustomProgressDialog;
import com.jiuzhe.commercial.view.MultipleChoiceDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by huanghao on 2018/4/25.
 */

public class AddHouseActivity extends BaseActivity implements LocationSource, AMapLocationListener {
    @BindView(R.id.et_city)
    TextView etCity;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_house)
    EditText etHouse;
    @BindView(R.id.et_price)
    TextView tvPrice;
    @BindView(R.id.et_lat)
    TextView etLat;
    @BindView(R.id.et_lng)
    TextView etLng;
    @BindView(R.id.ll_facility)
    LinearLayout llFacility;
    AMap mAmap;
    @BindView(R.id.map)
    MapView mMap;
    AMapLocationClient mLocationClient;
    OnLocationChangedListener mListener;
    // 声明mLocationOption对象
    AMapLocationClientOption mLocationOption;
    Boolean isFirstLoc = true;
    @BindView(R.id.ib_choice)
    ImageView ibChoice;
    @BindView(R.id.tv_state)
    TextView tvState;
    @BindView(R.id.iv_wifi)
    ImageView ivWifi;
    @BindView(R.id.iv_bed)
    ImageView ivBed;
    @BindView(R.id.iv_bathroom)
    ImageView ivBathroom;
    @BindView(R.id.iv_window)
    ImageView ivWindow;
    private String latitude;
    private String longitude;
    private CustomPopWindow mCustomPopWindow;
    private String mDepositPrice;
    private String mDayPrice;
    private List<String> facilityList = new ArrayList<>();
    HouseInfoBean houseInfoBean = new HouseInfoBean();
    private CustomProgressDialog dialog;
    private Dialog alertDialog;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.add_house_activity);
        setTitle("添加房源");
        setRringTitle("下一步");
        showDialogBox();
        setOnClik();
    }

    private void showDialogBox() {
        alertDialog = new Dialog(this, R.style.EasyListDialogStyle);
        alertDialog.setContentView(R.layout.dialog_room_hint);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.CENTER);
         DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = this.getResources().getDisplayMetrics().widthPixels/5*4;
        window.setAttributes(lp);
        Button btOk = alertDialog.findViewById(R.id.bt_ok);
        btOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    private void setOnClik() {
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upLoadHouseInfo();
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMap.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (mAmap == null) {
            mAmap = mMap.getMap();
            setLocation();
        }
    }

    private void setLocation() {
        //设置显示定位按钮 并且可以点击
        UiSettings settings = mAmap.getUiSettings();
        mAmap.setLocationSource(this);//设置了定位的监听,这里要实现LocationSource接口
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听，这里要实现AMapLocationListener接口，AMapLocationListener接口只有onLocationChanged方法可以实现，用于接收异步返回的定位结果，参数是AMapLocation类型。
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //初始化定位参数
        //启动定位
        mLocationClient.startLocation();
    }


    @Override
    protected void loadData() {

    }

    @OnClick({R.id.et_city, R.id.et_price, R.id.ll_facility, R.id.ib_choice})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.et_city:
                //Intent intent = new Intent(this, CityListSelectActivity.class);
                //startActivityForResult(intent, 1);
                break;
            case R.id.et_price:
                setPrice();
                break;
            case R.id.ll_facility:
                getFacility();
                break;
            case R.id.ib_choice:
                showPopMenu();
                break;
        }
    }

    /**
     * 配套信息
     */
    private void getFacility() {
        ivWifi.setVisibility(View.INVISIBLE);
        ivBed.setVisibility(View.INVISIBLE);
        ivBathroom.setVisibility(View.INVISIBLE);
        ivWindow.setVisibility(View.INVISIBLE);
        new MultipleChoiceDialog.Builder(this)
                .setTitle("配套设施")
                .addList(new String[]{"101", "102", "103", "104"})
                .addListener(new MultipleChoiceDialog.ClickListener() {
                    @Override
                    public void OnFinishClick(List<String> data, List<Integer> data0) {
                        facilityList.clear();
                        facilityList.addAll(data);
                        for (String item : data) {
                            if ("101".equals(item)) {
                                ivWifi.setVisibility(View.VISIBLE);
                            } else if ("102".equals(item)) {
                                ivBed.setVisibility(View.VISIBLE);
                            } else if ("103".equals(item)) {
                                ivBathroom.setVisibility(View.VISIBLE);
                            } else {
                                ivWindow.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                }).show();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (data != null) {
                    String name = data.getStringExtra("diqu");
                    String lat = data.getStringExtra("lat");
                    String lng = data.getStringExtra("lng");
                    String regionId = data.getStringExtra("regionId");
                    houseInfoBean.setRegionId(regionId);
                    etCity.setText(name);
                    moveCenter(new LatLng(Double.valueOf(lat) * 0.000001, Double.valueOf(lng) * 0.000001));
                }
                break;
            default:
                break;
        }
    }

    private void moveCenter(LatLng latLng) {
        //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
        CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 15, 30, 0));
        //AMap类中提供，直接移动过去，不带移动过程动画
        mAmap.moveCamera(mCameraUpdate);
    }

    /**
     * 弹出下拉框
     */
    private void showPopMenu() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu, null);
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .create()
                .showAsDropDown(ibChoice, 0, 20);
    }


    private void handleLogic(View view) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()) {
                    case R.id.tv_online:
                        showContent = "可预定";
                        break;
                    case R.id.tv_care:
                        showContent = "维护中";
                        Resources resources=getBaseContext().getResources();
                        Drawable drawable=resources.getDrawable(R.drawable.bg_care);
                        tvState.setBackground(drawable);
                        break;
                    case R.id.tv_sold:
                     //   showContent = "已下架";
                        break;
                }
                tvState.setText(showContent);
            }
        };
        view.findViewById(R.id.tv_online).setOnClickListener(listener);
        view.findViewById(R.id.tv_care).setOnClickListener(listener);
        view.findViewById(R.id.tv_sold).setOnClickListener(listener);
    }

    /**
     * 设置价格
     */
    private void setPrice() {
        final Dialog alertDialog = new Dialog(this, R.style.EasyListDialogStyle);
        mView = LayoutInflater.from(this).inflate(R.layout.dialog_house_price, null);
        alertDialog.setContentView(mView);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = this.getResources().getDisplayMetrics().widthPixels/5*4;
        window.setAttributes(lp);
        final EditText etDayPrice = alertDialog.findViewById(R.id.et_day_price);
        final EditText etDeposit = alertDialog.findViewById(R.id.et_deposit);
        Button btnCancel = alertDialog.findViewById(R.id.btn_cancel);
        Button btnOk = alertDialog.findViewById(R.id.bt_ok);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_cancel:
                        alertDialog.dismiss();
                        break;
                    case R.id.bt_ok:
                        mDayPrice = etDayPrice.getText().toString().trim();
                        mDepositPrice = etDeposit.getText().toString().trim();
                        if (!TextUtils.isEmpty(mDayPrice) && !TextUtils.isEmpty(mDepositPrice)) {
                            tvPrice.setText("日价" + mDayPrice + "元" + "   " + "压金" + mDepositPrice + "元");
                            alertDialog.dismiss();
                        } else {
                            UIUtils.showToastSafe("日价和压金价格不能为空");
                        }
                        break;
                }
            }
        };
        alertDialog.findViewById(R.id.bt_ok).setOnClickListener(listener);
        alertDialog.findViewById(R.id.btn_cancel).setOnClickListener(listener);
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                double latitude = aMapLocation.getLatitude();
                double longitude = aMapLocation.getLongitude();//获取经度
              //  houseInfoBean.setLat((int)(latitude*1000000));
             //   houseInfoBean.setLng((int)(longitude*1000000));
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息

                // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                StringBuffer buffer = null;
                if (isFirstLoc) {
                    //设置缩放级别
                    mAmap.moveCamera(CameraUpdateFactory.zoomTo(15));
                    //将地图移动到定位点
                    mAmap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));

                    //点击定位按钮 能够将地图的中心移动到定位点
                    //   mListener.onLocationChanged(aMapLocation);
                    isFirstLoc = false;
                    MarkerOptions markerOption = new MarkerOptions();
                    markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));//设置图标
                    markerOption.position(new LatLng(latitude, longitude));
                    markerOption.draggable(true);
                    mAmap.addMarker(markerOption);
                    buffer = new StringBuffer();
                    buffer.append(aMapLocation.getDistrict() + ""
                            + aMapLocation.getStreet() + ""
                            + aMapLocation.getStreetNum());
                }
                //   etCity.setText(aMapLocation.getProvince() + aMapLocation.getCity());
                //  etAddress.setText(buffer.toString());
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                Toast.makeText(this, "定位失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 上传房源
     */
    private void upLoadHouseInfo() {
        String houseCity = etCity.getText().toString().trim();
        String houseAddress = etAddress.getText().toString().trim();
        String houseName = etHouse.getText().toString().trim();
        String housePrice = tvPrice.getText().toString().trim();
        String houseLat = etLat.getText().toString().trim();
        String houseLng = etLng.getText().toString().trim();
        if (TextUtils.isEmpty(houseCity)) {
            UIUtils.showToastSafe("请选择当前城市地区！");
            return;
        }
        if (TextUtils.isEmpty(houseAddress)) {
            UIUtils.showToastSafe("请输入当前详细地址！");
            return;
        }
        if (TextUtils.isEmpty(houseName)) {
            UIUtils.showToastSafe("请输入当前民宿名称！");
            return;
        }
        if (TextUtils.isEmpty(houseLat)) {
            UIUtils.showToastSafe("请输入当前民宿经度！");
            return;
        }
        if (TextUtils.isEmpty(houseLng)) {
            UIUtils.showToastSafe("请输入当前民宿纬度！");
            return;
        }

        if (TextUtils.isEmpty(housePrice)) {
            UIUtils.showToastSafe("请输入当前民宿价格！");
            return;
        }

        if (facilityList!=null && facilityList.size()>0 ) {

        }else {
            UIUtils.showToastSafe("请选择当前民宿配套设施！");
            return;
        }
       houseInfoBean.setAddress(houseAddress);
       houseInfoBean.setSkuName(houseName);
        houseInfoBean.setLat(Integer.parseInt(houseLat));
        houseInfoBean.setLng(Integer.parseInt(houseLng));
       houseInfoBean.setRoomBond(mDepositPrice);  //压金
       houseInfoBean.setRoomPrice(mDayPrice);  //房间价格
       houseInfoBean.setMerchantId(SPUtil.getString(this, Constants.MERCHANTID));
       houseInfoBean.setSkuId(UIUtils.getUUID());
       houseInfoBean.setFacilityIdList(facilityList);
       if (tvState.getText().toString().trim().equals("可预定")){
           houseInfoBean.setRoomStatus("1");
       }else {
           houseInfoBean.setRoomStatus("4");
       }
        Intent intent = new Intent(this,AddPhotoActivity.class);
        intent.putExtra("room",(Serializable)houseInfoBean);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMap != null) {
            mMap.onDestroy();
        }
        if (mLocationClient != null) {
            mLocationClient.stopLocation();//停止定位
            mLocationClient.onDestroy();
        }//销毁定位客户端。
        if (dialog != null){
            dialog = null;
        }
    }
}